package com.chzu.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @Author lz
 * @Version 1.0
 * @Company 滁州大健康与养老产业研究院
 * @ClassName JsonResult
 * @Description 全局统一返回结果
 * @Date 2022/01/27 14:48
 */
@Data
@ApiModel(value = "全局统一返回结果")
public class JsonResult<T> {
    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private T data;

    public JsonResult(){}

    protected static <T> JsonResult<T> build(T data) {
        JsonResult<T> result = new JsonResult<T>();
        if (data != null){
            result.setData(data);
        }
        return result;
    }

    public static <T> JsonResult<T> build(T body, ResultCodeEnum resultCodeEnum) {
        JsonResult<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    public static <T> JsonResult<T> build(Integer code, String message) {
        JsonResult<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static<T> JsonResult<T> ok(){
        return JsonResult.ok(null);
    }

    /**
     * 操作成功
     * @param data
     * @param <T>
     * @return
     */
    public static<T> JsonResult<T> ok(T data){
        JsonResult<T> result = build(data);
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static<T> JsonResult<T> ok(String message, T data){
        JsonResult<T> result = build(null);
        result.setMessage(message);
        result.setData(data);
        return result;
    }

    public static<T> JsonResult<T> fail(){
        return JsonResult.fail(null);
    }

    public static<T> JsonResult<T> fail(String message){
        JsonResult<T> result = build(null);
        result.setMessage(message);
        return result;
    }

    /**
     * 操作失败
     * @param data
     * @param <T>
     * @return
     */
    public static<T> JsonResult<T> fail(T data){
        JsonResult<T> result = build(data);
        return build(data, ResultCodeEnum.FAIL);
    }

}

